

// -------百度地图API调用相关功能开始--------//
var map = new BMap.Map("map_box");    // 创建Map实例
map.centerAndZoom(new BMap.Point(116.404, 39.915), 15);  // 初始化地图,设置中心点坐标和地图级别
//添加地图类型控件
map.addControl(new BMap.MapTypeControl({
  mapTypes:[
          BMAP_NORMAL_MAP,
          BMAP_HYBRID_MAP
      ]}));   
// map.setCurrentCity("北京");          // 设置地图显示的城市 此项是必须设置的
map.enableScrollWheelZoom(true);
map.enableAutoResize();
var geoc = new BMap.Geocoder();  //地理位置逆解析

// 百度地图地址搜索功能
var local = new BMap.LocalSearch(map, {
    renderOptions:{map: map}
  });
var search_map=function(addr){
  // console.log(addr)
  local.search(addr);
}


var bd_map_marker_obj_list={};

//百度地图添加设备marker覆盖物功能函数

var add_device_marker_bdmap=function(obj,info_window='open'){
  
  var model=obj.model
  var user_detail=obj.user_detail
  var obj_name=obj.user_name
  var device_id=obj.device_id
  var marker_icon='/static/show_icon/'+user_detail.icon+'.png'
  if(info_window=='no'){
    marker_icon='/static/img/trail.png'
  }
  var point
  point=new BMap.Point(obj.lng,obj.lat)
  // 判断设备是否上传wg84的卫星递定位经纬度
  // var wgs84=dev_model_objs[model].datakind.wgs84
  // console.log(wgs84)
  // if(wgs84=='无'){
  //   return
  // }
  // 地址逆解析
  get_bdmap_addr(point,device_id)
  if(obj_name==''){
    obj_name=obj['device_id']
  }
  myIcon = new BMap.Icon(marker_icon, new BMap.Size(50,50),{anchor : new BMap.Size(20, 42),imageSize:new BMap.Size(50, 50)});
  // myIcon = new BMap.Icon(marker_icon, new BMap.Size(72,144),{imageSize:new BMap.Size(30, 30)});
  var marker = new BMap.Marker(point,{icon:myIcon});
  marker.self_detail=obj
  // 点击响应事件
  marker.addEventListener('click', function (e) {
    if(info_window=='open'){
      open_device_infowindow(e.target.self_detail,e.point)
    }
    // else{
    //   var lng=e.target.self_detail.dynamic.lng
    //   var lat=e.target.self_detail.dynamic.lat
    //   e.target.self_detail.dynamic.device_id=e.target.self_detail.device_id
    //   var pt=new BMap.Point(parseFloat(lng),parseFloat(lat))
    //   open_simple_infowindow(e.target.self_detail.dynamic,pt)
    // }
  })
  map.addOverlay(marker);//加载定位点
  bd_map_marker_obj_list[obj['device_id']]=marker;//汇集添加到地图的marker，方便移除和其他操作
  marker.setTitle(obj['device_id']);//设置标题
  var lb_html='<button class="layui-btn layui-btn-xs" style="border-radius:10px">'+obj_name+'</button>'
  var mylabel=new BMap.Label(lb_html,{offset:new BMap.Size(-3,-25)});
  mylabel.setStyle({border:'0',borderRadius:"10px"})
  marker.setLabel(mylabel);
  if(info_window=='open'){
    setTimeout(function(){open_device_infowindow(obj,point)},500)
  }
  map.centerAndZoom(point, 16);
  return marker
};


//删除地图定位点
var remove_marker_bdmap=function(key_field){
  var m=bd_map_marker_obj_list[key_field];
  map.removeOverlay(m);
  map.closeInfoWindow();
};

// 地址逆解析，从经纬度变成文字地址，百度接口
var all_addr_obj={};
var get_bdmap_addr=function(pt,key_field){
  var location
  geoc.getLocation(pt, function(rs){
    var addComp = rs.address
    if(rs.surroundingPois.length!=0){
      // console.log(rs)
       location=addComp+','+rs.surroundingPois[0]['title'] 
    }else{
       location=addComp
    }
    all_addr_obj[key_field]=location;
  });
};

// 画线功能
var draw_line_bdmap=function(pts){
  var polyline = new BMap.Polyline(pts, {
      strokeColor:"#18a45b",//设置颜色
      strokeWeight:8 ,//宽度
      strokeOpacity:0.8,//折线的透明度，取值范围0 - 1
      enableEditing: false,//是否启用线编辑，默认为false
      enableClicking: false,//是否响应点击事件，默认为true
      // icons:[icons]
  });
  map.addOverlay(polyline);
  map.setViewport(pts);
  return polyline
}

// 手动路线和轨迹路线，需要进行均匀切割，获取指定步长的点，方便后台进行路线偏移计算，pts：点数组，step：步长
var get_point_of_polyline=function(pts,step){
  var res=[]
  res.push([pts[0].lng,pts[0].lat])
    // 获取两点距离
  function _getDistance(pxA, pxB) {
      return Math.sqrt(Math.pow(pxA.x - pxB.x, 2) + Math.pow(pxA.y - pxB.y, 2));
  };

  // 在转墨卡托坐标之后，本次移动的目标坐标点，初始坐标点的值+本次移动序号/总移动次数*（目标坐标点-初始坐标点）
  function effect(initPos, targetPos, currentCount, count) {
    var b = initPos, c = targetPos - initPos, t = currentCount,
    d = count;
    return c * t / d + b;
  }
  for(var i=0;i<pts.length-1;i++){
    var initPos=pts[i]
    var targetPos=pts[i+1]
      // 移动间隔时间
      timer = 10;
      //步长，米/次
      //初始坐标
      init_pos = map.getMapType().getProjection().lngLatToPoint(initPos);
      //获取结束点的(x,y)坐标
      target_pos = map.getMapType().getProjection().lngLatToPoint(targetPos);
      //两个点之间需要移动的总次数
      count = Math.round(_getDistance(init_pos, target_pos) / step);

      if(count==0){
        count=1
      }
      // 每两个点之间的距离大于步长的，进行均匀切割
      for(var n=1;n<count+1;n++){
        // console.log(n,count)
        var x = effect(init_pos.x, target_pos.x, n, count),
            y = effect(init_pos.y, target_pos.y, n, count),
            pos = map.getMapType().getProjection().pointToLngLat(new BMap.Pixel(x, y));
        res.push([pos.lng,pos.lat])
        //判断是否还继续递归
      }
  }

  console.log('end',res)
  return res

}

// 沿线平滑移动
var move_on_line=function(trail_opt,setSlider=''){
  var pts=trail_opt['tarckpoint']
  var mover=trail_opt['carMk']
  var point_num=pts.length
  var marker_move=function(i) {
    var initPos=pts[i]
    var targetPos=pts[i+1]
    var point_num=pts.length;
    
    // 获取两点距离
    function _getDistance(pxA, pxB) {
        return Math.sqrt(Math.pow(pxA.x - pxB.x, 2) + Math.pow(pxA.y - pxB.y, 2));
    };
    // wgs84坐标转换为墨卡托坐标
    function _getMercator(poi) {
        return map.getMapType().getProjection().lngLatToPoint(poi);
    };
    // 在转墨卡托坐标之后，本次移动的目标坐标点，初始坐标点的值+本次移动序号/总移动次数*（目标坐标点-初始坐标点）
    function effect(initPos, targetPos, currentCount, count) {
      var b = initPos, c = targetPos - initPos, t = currentCount,
      d = count;
      return c * t / d + b;
    }
      //当前的帧数
      currentCount = 0;
      // 移动间隔时间
      timer = 10;
      //步长，米/次
      step = trail_opt['play_speed'] / (1000 / timer);
      //初始坐标
      init_pos = map.getMapType().getProjection().lngLatToPoint(initPos);
      //获取结束点的(x,y)坐标
      target_pos = map.getMapType().getProjection().lngLatToPoint(targetPos);
      //两个点之间需要移动的总次数
      count = Math.round(_getDistance(init_pos, target_pos) / step);
    if(setSlider!=''){
      setSlider(((i+1)/point_num), 'trail_progress');
    }
    intervalFlag = setInterval(function() {
    //两点之间当前帧数大于总帧数的时候，则说明已经完成移动
        if (currentCount >count | count < 1) {
            clearInterval(intervalFlag);
            i++
            // 当前运行的轨迹点做自增加记录
            trail_opt['current_pt']++;
            // console.log(i,trail_opt,point_num)
            if(i>point_num){
              return 
            }
            move_next(i)
            
        }else {
                currentCount++;
                var x = effect(init_pos.x, target_pos.x, currentCount, count),
                    y = effect(init_pos.y, target_pos.y, currentCount, count),
                    pos = map.getMapType().getProjection().pointToLngLat(new BMap.Pixel(x, y));
                // 设置marker
                if(currentCount == 1){
                    var pt_label=mover.getLabel()
                    pt_label.setContent(initPos['html']);
                    mover.setLabel(pt_label);

                    if(!map.getBounds().containsPoint(pos)){
                      map.panTo(pos);
                    } 
                }
                //正在移动
                console.log(targetPos['dev_datail'].dirct)
                mover.setRotation(targetPos['dev_datail'].dirct)
                mover.setPosition(pos);
                

                //设置自定义overlay的位置
            }
    },timer);
  };
  // 递归判断条件，上一个点移动完毕，判断是否还有下一个点需要移动
  var move_next=function(num){
    if(num <= point_num-2 && trail_opt['status']=='run'){
      marker_move(num)
    }else{
      if(trail_opt['current_pt']>=point_num-2){
        trail_opt['current_pt']=0
        trail_opt['status']='stop'
      }
      if(setSlider!=''){
        setSlider((1), 'trail_progress');
      }
    }
  }

  // 控制
  // 停止状态和首次运行状态，启动轨迹
  if(trail_opt['status']=='f_run' | trail_opt['status']=='stop'){
    trail_opt['status']='run';
    trail_opt['current_pt']=0
    marker_move(0)
  // 正在运行轨迹的状态，点击play无效
  }else if(trail_opt['status']==='run'){
    return
  // 按下暂停，记录暂停状态，再点击播放，从暂停处开始播放
  }else{
    if(trail_opt['current_pt']>=point_num){
      trail_opt['current_pt']=0
    }
    trail_opt['status']='run'
    marker_move(trail_opt['current_pt'])
  }
}

//设备定位点信息窗展示功能
var current_open_device_infowindow;
var open_device_infowindow=function(gps,point=''){
  // console.log(gps)
  if(point==''){
    point=new BMap.Point(gps.dynamic.lng,gps.dynamic.lat)
  }
  var bds_num=0,gps_num=0,rssi=0;
  var param1,param2,param3,param4;
  var track_type=gps.dynamic.track_type;
  if(track_type='satelite'){
    track_type='卫星定位'
  }else if (track_type='0'){
    track_type='未定位'
  }

  var dev_loca=all_addr_obj[gps.device_id]
  // var status_list=['acc_off', 'ante_ok', 'undefence', 'normal','online','sleep']
  status_dict={'undefence':'未设防', 
                'normal':'正常',
                'online':'<font color="green">在</font>',
                'sleep':'<font color="blue">休</font>',
                'sos_alarm':'<font color="red">sos</font>',
                'offline':'<font color="black">离</font>'}
  var rssi_status=gps.dynamic.rssi_status
  if(rssi_status!=null){
    bds_num=rssi_status['bds']
    gps_num=rssi_status['gps']
    rssi=rssi_status['gsm']
  }
  var stop_time=gps.dynamic.stop_time
  if(stop_time!='0'){
    stop_time=(stop_time/3600).toFixed(1)
  }
  var mileage=gps.dynamic.mileage
  if(mileage==null){
    mileage=''
  }
  var status=''
  for(i=0;i<gps.status.length;i++){
    status=status+' '+status_dict[gps.status[i]]
  }

  if(gps.alarm_status!='no'){
    status=status+' '+'<font color="red">警</font>'
  }

  // 绑定的用户信息
  var user_detail=gps.user_detail;
  var dev_user_name=gps.user_name;
  var param1=user_detail.customize_title1+'：'+user_detail.customize_value1
  var param2=user_detail.customize_title2+'：'+user_detail.customize_value2
  var param3=user_detail.customize_title3+'：'+user_detail.customize_value3

  //信息窗口参数722,1536
  // console.log(get_height,get_width)
  var opts = {
    width : 300,     // 信息窗口宽度
    height: 280,     // 信息窗口高度
    offset:new BMap.Size(0, -32)
    };
  var info_window_baidu;
  info_window_baidu=
   "<div style='margin:0;padding:0;border-radius:20px'>"+
    "<table class='layui-table' lay-size='sm'  style='font-size:10px;margin:0px 0px 0px 0px;padding:0px 0px 0px 0px;'>"+
    "<tbody>"+
    "<tr>"+
      "<td colspan=2 bgcolor='#009688' style='height:15px'><font color='white'>"+dev_user_name+','+param1+','+param2+','+param3+"</font></td>"+
    "</tr>"+

    "<tr >"+
    "<td colspan=2 style='height:15px'><font>"+"设备ID : "+gps.device_id+"</font></td>"+
    "</tr>"+
    "<tr>"+
    "<td colspan=2>"+
    "<div class='layui-row'>"+
    "<div class='layui-col-lg4'>"+status+"</div>"+
    "<div class='layui-col-lg8'>"+
    "<i class='fa fa-battery-full pull-right' style = 'font-size:10px; padding-right: 9px;color: #009688;' > "+gps.battery+"</i>"+
    "<i class='fa fa-broadcast-tower pull-right'  style = 'font-size:10px; padding-right: 9px;color: #009688;'>"+rssi+"</i>"+
    "<i class='fa fa-satellite-dish pull-right'  style = 'font-size:10px; padding-right: 9px;color: #009688;'>"+gps_num+"</i>"+
    "<i class='fa fa-satellite pull-right'  style = 'font-size:10px; padding-right: 1px;color: #009688;'>"+bds_num+"</i>"+
    "</div>"+
    "</div>"+
    "</td>"+
    "<tr>"+"<td>速度："+gps.dynamic.speed+" km/h</td>"+"<td>里程 : "+mileage+" 公里</td>"+
    "</tr>"+
    "<tr>"+"<td>停留："+stop_time+" 小时</td>"+"<td>定位 : "+track_type+"</td>"+
    "</tr>"+
    "<tr>"+
    "<td colspan=2>时间："+gps.serv_receive+"</td>"+
    "</tr>"+
    "<tr>"+
    "<td colspan=2>位置："+all_addr_obj[gps.device_id]+"</td>"+
    "</tr>"+

      "</tbody>"+
  "</table>"+ 
    "<br>"+
    "<button class='layui-btn layui-btn-xs' onclick='turn_to_page(\"trail\")'>"+
      '<i class="layui-icon ">&#xe715;</i>'+
      "轨迹"+
    "</button>"+
    "<button class='layui-btn layui-btn-xs ' onclick='set_param("+gps.device_id+")'>"+
      '<i class="layui-icon ">&#xe667;</i>'+
      "报警"+
    "</button>"+
    "<button class='layui-btn layui-btn-xs' onclick='command_modal("+gps.device_id+")'>"+
      '<i class="layui-icon ">&#xe601;</i>'+
      "命令"+
    "</button>"+
    "<button class='layui-btn layui-btn-xs' onclick='device_set_modal("+gps.device_id+")'>"+
      '<i class="layui-icon ">&#xe614;</i>'+
      "设置"+
    "</button>"+
    "<button class='layui-btn layui-btn-xs' onclick='turn_to_page(\"tracking\")'>"+
      '<i class="layui-icon ">&#xe64c;</i>'+
      "追踪"+
    "</button>"+
  "</div>"
  ;
  var gpsinfoWindow = new BMap.InfoWindow(info_window_baidu, opts,{anchor : new BMap.Size(20, 42)});
  gpsinfoWindow.addEventListener('close', function(){
      current_open_device_infowindow=null
  })
  map.openInfoWindow(gpsinfoWindow,point);
  current_open_device_infowindow=gps.device_id
};


//简易信息窗口
var open_simple_infowindow=function(tp){
  //信息窗口参数
  var gps_num=tp.gps_num,bds_num=tp.bds_num;
  if(gps_num==null){
    gps_num='0'
  }
  if(bds_num==null){
    bds_num='0'
  }

  var opts = {
    width : 30,     // 信息窗口宽度
    height: 200,     // 信息窗口高度
    };

  var p=
    "<div style='margin:0;padding:0;'>"+
      "<table class='layui-table' lay-size='sm' lay-skin='nob' style='margin:0;padding:0'>"+
        "<tr>"+
          "<td colspan=2>"+
          "<div class='layui-btn-group'>"+
            "<i class='fa fa-battery-full pull-right' style = 'font-size:10px; padding-right: 9px;color: #009688;' > "+tp.battery+"</i>"+
            "<i class='fa fa-broadcast-tower pull-right'  style = 'font-size:10px; padding-right: 9px;color: #009688;'>"+tp.rssi+"</i>"+
            "<i class='fa fa-satellite-dish pull-right'  style = 'font-size:10px; padding-right: 9px;color: #009688;'>"+gps_num+"</i>"+
            "<i class='fa fa-satellite pull-right'  style = 'font-size:10px; padding-right: 1px;color: #009688;'>"+bds_num+"</i>"+
          "</div>"+
          "</td>"+
        "</tr>"+
        "<tr>"+
          "<td>"+
            "里程："+tp.mileage+"公里"+
          "</td>"+
          "<td>"+
            "速度："+tp.speed+"km/h"+
          "</td>"+
        "</tr>"+
        "<tr>"+
         "<td>"+
            "方向："+tp.dirct+"°"+
          "</td>"+
          "<td>"+
            "类型："+tp.track_type+
          "</td>"+
        "</tr>"+
        "<tr>"+
          "<td colspan='2'>"+
            "时间："+tp.serv_receive+
          "</td>"+
        "</tr>"+
        "<tr>"+
          "<td colspan='2'>"+
            "位置："+all_addr_obj[tp.device_id]+
          "</td>"+
        "</tr>"+
      "</table>"+
    "</div>";
    var gpsinfoWindow = new BMap.InfoWindow(p, opts);

    // gpsinfoWindow.open()
    var point=new BMap.Point(tp.lng,tp.lat)
    map.openInfoWindow(gpsinfoWindow,point);    
};

 var navigationControl = new BMap.NavigationControl({
    // 靠右上角位置
    anchor: BMAP_ANCHOR_TOP_RIGHT,
    // LARGE类型
    type: BMAP_NAVIGATION_CONTROL_LARGE,
    // 启用显示定位
    enableGeolocation: true,
    offset:new BMap.Size(0,55)
  });
  map.addControl(navigationControl);
  // 添加定位控件

var geolocationControl = new BMap.GeolocationControl();
  geolocationControl.addEventListener("locationSuccess", function(e){
    // 定位成功事件
    var address = '';
    address += e.addressComponent.province;
    address += e.addressComponent.city;
    address += e.addressComponent.district;
    address += e.addressComponent.street;
    address += e.addressComponent.streetNumber;
    alert("当前定位地址为：" + address);
  });
  geolocationControl.addEventListener("locationError",function(e){
    // 定位失败事件
    alert(e.message);
  });
  map.addControl(geolocationControl);